package com.sudo.boot.admin.config;

import cn.dev33.satoken.exception.*;
import cn.dev33.satoken.sso.exception.SaSsoException;
import com.sudo.boot.base.pojo.JsonRes;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Boot全局异常拦截
 *
 * @author DayDayUp
 * @datetime 2023-10-13 17:12
 **/
@Slf4j
@Order(1)
@RestControllerAdvice
public class BootGlobalExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = NotLoginException.class)
    public JsonRes<String> handlerThrowable(NotLoginException e) {
        log.error("未登录异常：",e);
        return new JsonRes<>(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NotPermissionException.class)
    public JsonRes<String> handlerException(NotPermissionException e) {
        log.error("缺少权限异常：",e);
        return new JsonRes<>(HttpStatus.FORBIDDEN.value(), "缺少权限：" + e.getPermission());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NotRoleException.class)
    public JsonRes<String> handlerException(NotRoleException e) {
        log.error("缺少角色异常：",e);
        return new JsonRes<>(HttpStatus.FORBIDDEN.value(), "缺少角色：" + e.getRole());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NotSafeException.class)
    public JsonRes<String> handlerException(NotSafeException e) {
        log.error("二级认证校验失败异常：",e);
        return new JsonRes<>(HttpStatus.FORBIDDEN.value(), "缺少角色：" + e.getService());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(DisableServiceException.class)
    public JsonRes<String> handlerException(DisableServiceException e) {
        log.error("服务封禁异常：",e);
        String msg = "当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封";
        return new JsonRes<>(HttpStatus.FORBIDDEN.value(), msg);
    }

    // 拦截：Http Basic 校验失败异常
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NotBasicAuthException.class)
    public JsonRes<String> handlerException(NotBasicAuthException e) {
        log.error("Http Basic 校验失败异常：",e);
        return new JsonRes<>(500, e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(SaSsoException.class)
    public JsonRes<String> handlerSaSsoException(SaSsoException e) {
        log.error("单点登录异常：",e);
        return new JsonRes<>(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
    }
}
